package com.example.room.repository;

import android.content.Context;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import com.example.room.dao.MyJoinTeamDao;
import com.example.room.dao.TeamDao;
import com.example.room.database.MyDatabase;
import com.example.room.entity.MyJoinTeam;
import com.example.room.entity.Team;

import java.util.List;

public class MyJoinTeamRepository {
    MyJoinTeamDao myJoinTeamDao;

    LiveData<List<MyJoinTeam>> teams;

    public MyJoinTeamRepository(Context context) {
        MyDatabase database = MyDatabase.getInstance(context.getApplicationContext());
        myJoinTeamDao = database.getMyJoinTeamDao();
        teams = myJoinTeamDao.getAllTeam();
    }

    public LiveData<List<MyJoinTeam>> getAllTeam() {
        return teams;
    }


    public void insertTeam(MyJoinTeam... teams){
        new InsertMyJoinTeamAsyncTask(myJoinTeamDao).execute(teams);
    }

    //内部类，用于在子线程中访问数据库，如果有多个操作的话，每一个操作都要对应一个AsyncTask
    static class InsertMyJoinTeamAsyncTask extends AsyncTask<MyJoinTeam,Void,Void> {
        private MyJoinTeamDao myJoinTeamDao;

        public InsertMyJoinTeamAsyncTask(MyJoinTeamDao teamDao) {
            this.myJoinTeamDao = teamDao;
        }

        @Override
        protected Void doInBackground(MyJoinTeam... teams) {
            myJoinTeamDao.insertTeam(teams);
            return null;
        }
    }

    public void deleteAllTeam() {
        new DeleteMyJoinTeamAsyncTask(myJoinTeamDao).execute();
    }
    public static class DeleteMyJoinTeamAsyncTask extends AsyncTask<Void,Void,Void> {

        private MyJoinTeamDao myJoinTeamDao;

        public DeleteMyJoinTeamAsyncTask(MyJoinTeamDao myJoinTeamDao) {
            this.myJoinTeamDao = myJoinTeamDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            myJoinTeamDao.deleteAllTeam();
            return null;
        }
    }
}
